package com.csxy.systemmanager.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.csxy.systemmanager.common.ResponseResult;
import com.csxy.systemmanager.entity.User;
import com.csxy.systemmanager.service.LoginService;
import com.csxy.systemmanager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {

    //注入service
    @Autowired
    public LoginService loginService;
    @Autowired
    public UserService userService;


    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user) {
        //调用service
        return loginService.login(user);
    }


    @RequestMapping("/logout")
    public ResponseResult logout() {
        //调用service
        return loginService.logout();
    }

    @GetMapping("/currentUser")
    public ResponseResult getCurrentUser() {
        //调用service
        return userService.getCurrentUser();
    }

    @GetMapping("/userList")
    //当前页  每页显示数量
    public ResponseResult getUserListByPage(Integer current, Integer size,String query) {
        //调用service
        IPage<User> page = userService.getUserListByPage(current, size, query);
        return new ResponseResult(200, "ok", page);
    }

    /**
     * 新增用户
     */
    @PutMapping()
    public ResponseResult addUser(@RequestBody User user) {
        //用户的创建时间
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));

        return userService.addUser(user);
    }

    /**
     * 修改用户
     */
    @PostMapping()
    public ResponseResult updateUser(@RequestBody User user) {
        boolean save = userService.updateById(user);

        if (save) {
            return new ResponseResult(200, "ok");
        }

        return new ResponseResult(500, "用户保存失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping()
    public ResponseResult deleteUser(@RequestBody String id) {
        boolean remove = userService.removeById(id);

        if (remove) {
            return new ResponseResult(200, "ok");
        }

        return new ResponseResult(500, "用户删除失败");
    }
}
